import axios, { AxiosError, AxiosResponse, InternalAxiosRequestConfig } from '@ohos/axios';

const request = axios.create({
  //远程服务器
  baseURL: 'http://120.26.90.87:8080',
  //本地服务器
  // baseURL: 'http://10.0.2.2:8080', // 模拟器上使用
  // baseURL: 'http://localhost:8080', // 预览器上使用
  timeout: 20000,
})

request.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 未来需要添加 token
    // config.headers.token = token;
    return config;
  }
)

request.interceptors.response.use(
  (response: AxiosResponse) => {
    if (response.data.code === 1) {
      return response.data.data;
    } else {
      return Promise.reject(response.data.message);
    }
  },
  (error: AxiosError) => {
    return Promise.reject(error.message);
  }
)

export default class Http {
  get<T>(url: string, params?: Object) {
    // console.log('自定义信息','正在发送get请求');
    return request.get<null, T>(url, {
      params
    })
  }

  post<T>(url: string, data?: Object) {
    console.log('自定义信息','正在发送post请求')
    return request.post<null, T>(url, data)
  }

  put<T>(url: string, data?: Object) {
    console.log('自定义信息','正在发送put请求')
    return request.put<null, T>(url, data)
  }

  delete<T>(url: string, params?: Object) {
    return request.delete<null, T>(url, {
      params
    })
  }
};